#include "event.h"
#include "cmsis_os2.h"

Event::Event()
{
    CreateEvent();
}

Event::~Event()
{
    DeleteEvent();
}

void Event::Set(uint32_t flags)
{
    osEventFlagsSet(m_eventHandle, flags);
}

uint32_t Event::Get()
{    
    return osEventFlagsGet(m_eventHandle);
}

void Event::Clear(uint32_t flags)
{
    osEventFlagsClear(m_eventHandle, flags);
}

uint32_t Event::WaitAny(uint32_t flags, bool clear, int timeout)
{
    uint32_t option = osFlagsWaitAny;
    if(clear == false)
        option |= osFlagsNoClear;
    return WaitImpl(flags, option, timeout);
}

uint32_t Event::WaitAll(uint32_t flags, bool clear, int timeout)
{
    uint32_t option = osFlagsWaitAll;
    if(clear == false)
        option |= osFlagsNoClear;
    return WaitImpl(flags, option, timeout);
}

uint32_t Event::WaitImpl(uint32_t flags, uint32_t option, int timeout)
{
    if(timeout == -1)
        timeout = osWaitForever;
    return osEventFlagsWait(m_eventHandle, flags, option, timeout);
}

void Event::CreateEvent()
{
    osEventFlagsAttr_t attr = {0};

    attr.name = "event";
    m_eventHandle = osEventFlagsNew(&attr);
}

void Event::DeleteEvent()
{
    osEventFlagsDelete(m_eventHandle);
}
